package org.hefan.org.service.impl;

import org.hefan.basic.service.impl.BaseServiceImpl;
import org.hefan.org.domain.Department;
import org.hefan.org.mapper.DepartmentMapper;
import org.hefan.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * DepartmentServiceImpl实现类
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    /**
     * 注入departmentMapper
     */
    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 重写部门保存方法
     * @param department
     */
    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.save(department);
        if (department.getParent() == null || department.getParent().getId() == null) { // 没有选择上级部门
            department.setDirPath("/" + department.getId()); //因为没有上级部门,所以设置dirPath为  /+自己的id
        } else { // 选择了上级部门
            Long id = department.getParent().getId(); // 获取上级部门的id
            Department parentDept = departmentMapper.loadById(id); // 通过上级部门id获取上级部门对象
            String dirPath = parentDept.getDirPath(); // 通过上级部门对象获取上级部门dirPath

            department.setDirPath(dirPath + "/" + department.getId()); // 设置当前这个子部门的dirPath为上级部门 dirPath + / + 自己的id
        }
        departmentMapper.update(department); // 修改数据库里自己的dirPath
    }

    /**
     * 重写部门修改方法
     * @param department
     */
    @Override
    @Transactional
    public void update(Department department) {
        if (department.getParent() == null || department.getParent().getId() == null) { // 没有选择上级部门
            department.setDirPath("/" + department.getId()); //因为没有上级部门,所以设置dirPath为  /+自己的id
        } else { // 选择了上级部门
            Long id = department.getParent().getId(); // 获取上级部门的id
            Department parentDept = departmentMapper.loadById(id); // 通过上级部门id获取上级部门对象
            String dirPath = parentDept.getDirPath(); // 通过上级部门对象获取上级部门dirPath
            department.setDirPath(dirPath + "/" + department.getId()); // 设置当前这个子部门的dirPath为上级部门 dirPath + / + 自己的id
        }
        departmentMapper.update(department);
    }

    /**
     * 查询部门树集合
     * @return Department的list集合
     */
    @Override
    public List<Department> getDeptTree() {
        return departmentMapper.getDeptTree();
    }

}
